<template>
  <view class="confirm-order">
    <view class="goods">
      <text>商品信息</text>
      <template v-if="course && course.list">
        <course-item v-for="(item,index) in course.list" :key="index" :item="item"></course-item>
      </template>
      <course-item v-else :item="course"></course-item>
    </view>

    <view class="option-pay card">
      <view class="title">
        支付方式
      </view>
      <view v-if="isIos" class="ios">
        <text>余额：</text>
        <text>{{balance}}币{{isEnoughPay ? '' : '(余额不足)'}}</text>
      </view>
      <radio-group v-else name="" @change="radioChange">
        <!-- #ifndef MP-ALIPAY -->
        <label class="pay-item center space-between">
          <view class="left center">
            <image src="/static/pay/wxpay.png" mode=""></image>
            <text>微信支付</text>
          </view>
          <radio value="wxpay" :checked="provider === 'wxpay'" style="transform: scale(0.8);" />
        </label>
        <!-- #endif -->

        <!-- #ifndef MP-WEIXIN -->
        <label class="pay-item center space-between">
          <view class="left center">
            <image src="/static/pay/alipay.png" mode=""></image>
            <text>支付宝支付</text>
          </view>
          <radio value="alipay" :checked="provider === 'alipay'" style="transform: scale(0.8);" />
        </label>
        <!-- #endif -->
      </radio-group>
    </view>

    <view class="card price">
      <view class="space-between">
        <text>商品金额</text>
        <text>￥{{course.priceOriginal || course.totalPrice}}</text>
      </view>
      <view class="space-between" v-if="course.priceDiscount || course.groupPrice">
        <text>优惠价</text>
        <text>￥{{course.priceDiscount || course.groupPrice}}</text>
      </view>
    </view>

    <view style="height: 130rpx;"></view>

    <view class="pay space-between">
      <view class="">
        <text class="grey">实付金额：</text>
        <text>￥{{resultFinalPrice}}</text>
      </view>

      <view class="">
        <button v-if="isIos" class="btn" :loading="loading" :disabled="loading"
          @click="iosPayHandler">{{isEnoughPay ?'立即支付' : '充值并支付'}}</button>
        <!-- #ifdef MP-WEIXIN -->
        <button v-else class="btn" :loading="loading" :disabled="loading" @click="wxPayHandler">提交订单</button>
        <!-- #endif -->

        <!-- #ifndef MP-WEIXIN -->
        <button v-else class="btn" :loading="loading" :disabled="loading" @click="payHandler">提交订单</button>
        <!-- #endif -->
      </view>
    </view>


  </view>
</template>

<script setup lang="ts">
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    ref,
    reactive,
    computed,
    getCurrentInstance
  } from 'vue'
  import courseItem from '@/components/common/course-item.vue'
  import api from '@/api/order.js'
  import apiCourse from '@/api/course.js'
  const {
    proxy
  } = getCurrentInstance()
  let course = ref({})
  let isIos = ref(false)
  let provider = ref('alipay')
  let loading = ref(false)
  let balance = ref(0)

  onLoad(async (option) => {
    // #ifdef H5
    option.course ? course.value = JSON.parse(decodeURIComponent(option.course.replace(/%/g, '%25'))) : course
      .value = JSON.parse(decodeURIComponent(option.courseGroup.replace(/%/g, '%25')))
    // #endif

    // #ifdef MP-WEIXIN
    option.course ? course.value = JSON.parse(decodeURIComponent(option.course)) : course.value = JSON.parse(
      decodeURIComponent(option.courseGroup))
    provider.value = 'wxpay';
    console.log(course.value);
    // #endif

    // #ifdef APP-PLUS
    let requestId = null;
    if (option.id) {
      requestId = JSON.parse(option.id)
      course.value = (await apiCourse.getCourseDetail(requestId)).data
    } else if (option.courseGroupId) {
      requestId = JSON.parse(option.courseGroupId)
      course.value = (await apiCourse.getGroupListbyId(requestId)).data
    }
    isIos.value = uni.getSystemInfoSync().platform === 'ios'
    if (isIos.value) {
      getBalance()
    }
    // #endif

  })


  const resultFinalPrice = computed(() => {
    return course.value.priceDiscount || course.value.groupPrice || course.value.priceOriginal || course.value
      .totalPrice
  })
  const isEnoughPay = computed(() => {
    return balance.value >= resultFinalPrice.value
  })

  // 查询ios端的余额事件
  const getBalance = async () => {
    const {
      data
    } = await api.getUserBalance()
    balance.value = data
  }

  // 切换点击事件
  const radioChange = (event) => {
    provider.value = event.detail.value
  }

  // ios支付
  const iosPayHandler = async () => {
    // 获取支付金额
    const price = resultFinalPrice.value
    // 获取课程ids
    let courseIds = []
    if (course.value.list) {
      course.value.list.forEach(item => {
        courseIds.push(item.courseId)
      })
    } else {
      courseIds.push(course.value.courseId)
    }

    // 提交后台的数据
    const data = {
      price,
      courseIds
    }

    // 判断是否余额不足
    if (!isEnoughPay.value) {
      proxy.navTo(`/pages/order/my-balance?parmas=${JSON.stringify(data)}`)
      return
    }

    loading.value = true
    uni.showLoading({
      title: "支付中",
      mask: true
    })
    const res = await api.orderPay(data)
    uni.hideLoading()

    if (res.code === 20000) {
      getBalance()
      uni.showModal({
        content: "支付完成，立即学习",
        showCancel: false,
        success: () => {
          proxy.navTo('/pages/order/order')
        }
      })
    } else {
      uni.showModal({
        content: "支付失败",
        showCancel: false
      })
    }
    loading.value = false
  }

  const loginWeiXinMp = () => {
    return new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          console.log('res', res.code);
          let openid = 'xxx'
          uni.setStorageSync("openid", openid)
          resolve(openid)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }


  // 微信小程序支付
  const wxPayHandler = async () => {
    loading.value = true
    let openid = uni.getStorageSync("openid")
    if (!openid) {
      try {
        openid = await loginWeiXinMp()
      } catch (e) {
        //TODO handle the exception
      }

      if (!openid) {
        uni.showModal({
          content: "获取openid失败",
          showCancel: false
        })
        loading.value = false
        return
      }
    }

    // 获取支付金额
    const price = resultFinalPrice.value
    // 获取课程ids

    let courseId = null;
    let groupId = null;
    if (course.value.courseId) {
      courseId = course.value.courseId
    } else if (course.value.groupId) {
      groupId = course.value.groupId
    }

    // 提交后台的数据
    const data = {
      price,
      courseId,
      groupId
    }

    let orderInfo = await api.weixinMPPay(data)

    uni.requestPayment({
      timeStamp: orderInfo.data.timeStamp,
      nonceStr: orderInfo.data.nonceStr,
      package: "prepay_id=" + orderInfo.data.prepay_id,
      signType: 'RSA',
      paySign: orderInfo.data.paySign,
      success(res) {},
      fail(res) {}
    })
  }

  // 安卓app支付
  const payHandler = () => {

  }
</script>

<style lang="scss" scoped>
  .confirm-order {
    font-size: 29rpx;
    color: #333;

    .goods {
      padding: 20rpx 30rpx 0 30rpx;
      background-color: #fff;
    }

    .card {
      padding: 0 30rpx;
      background-color: #fff;
      margin-top: 30rpx;
      box-shadow: 1px 0 5px 0 rgba(0, 0, 0, 0.08);
      border-radius: 20rpx;
    }

    .option-pay {
      .title {
        line-height: 90rpx;
        border-bottom: 0.5px solid #efeff4;
      }

      .ios {
        line-height: 90rpx;

        text:last-child {
          color: $mxg-text-color-red;
        }
      }

      .pay-item {
        line-height: 90rpx;

        .left {
          image {
            width: 60rpx;
            height: 60rpx;
          }

          text {
            padding-left: 23rpx;
            font-size: 33rpx;
          }
        }
      }
    }

    .price {
      >view {
        line-height: 90rpx;
        border-bottom: 1px solid #F8F9FB;
      }
    }

    .pay {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      align-items: center;
      height: 100rpx;
      padding: 0 30rpx;
      background-color: #fff;
      border-top: 0.5px solid #efeff4;

      view:first-child>text:last-child {
        color: $mxg-text-color-red;
        font-size: 35rpx;
      }

      .btn {
        background-color: $mxg-text-color-blue;
        color: #FFF;
        border-radius: 50rpx;
        line-height: 80rpx;
        font-size: 30rpx;

        &::after {
          border: none;
        }
      }

    }


  }
</style>
